#include "string.h"
#include "global.h"
#include "debug.h"

/*set value to dest_*/
void memset(void* dest_,uint8_t value,uint32_t size) {
	ASSERT(dest_ != NULL);
	uint8_t* dest = (uint8_t*)dest_;
	while(size-- > 0)
		*dest++ = value;
}

/*copy memory*/
void memcpy(void* dest_,const void* src_,uint32_t size) {
	ASSERT(dest_ != NULL && src_ != NULL);
	uint8_t* dest = (uint8_t*)dest_;
	const uint8_t* src = (uint8_t*)src_;
	while(size-- > 0)
		*dest++ = *src++;
}

/*compare a_ and b_, equal return 0, a_ > b_ return +1 ,else return -1 */
int memcmp(const void* a_,const void* b_,uint32_t size) {
	const char* a = a_;
	const char* b = b_;
	ASSERT(a != NULL && b != NULL);
	while(size-- > 0) {
		if(*a != *b)
			return *a > *b ? 1 : -1;
		a++;
		b++;
	}
	return 0;
}

/*copy string*/
char* strcpy(char* dest_,char* src_) {
	ASSERT(dest_ != NULL && src_ != NULL);
	char* res = dest_;   		//return the destination addr
	while((*dest_++ = *src_++));
	return res;
}

/*return string length*/
uint32_t strlen(const char* str) {
	ASSERT(str != NULL);
	const char* p = str;
	while(*p++);
        return (p - str -1);
}

/*compare two string a > b return 1,equal return 0,else retturn -1*/
int8_t strcmp(const char* a,const char* b) {
	ASSERT(a != NULL && b !=NULL);
	while(*a != 0 && *a == *b) {
		a++;
		b++;
	}
	return *a < *b ? -1 : *a > *b;
}

/*left to right return first addr of ch in string*/
char* strchr(const char* string, const uint8_t ch) {
	ASSERT(string != NULL);
	while(*string != 0) {
		if(*string == ch) {
			return (char*)string;
		}
           string++;
	}
        return NULL;
}

/*right to left return first addr of ch in string*/
char* strrchr(const char* string, const uint8_t ch) {
	ASSERT(string != NULL);
        const char* last_char = NULL;
	while(*string != 0) {
		if(*string == ch)
			last_char = string;
		string++;
	}
	return (char*)last_char;
}

/*append src_ to dst_*/
char* strcat(char* dst_,const char* src_) {
	ASSERT(dst_ != NULL && src_ != NULL);
	char* str = dst_;
	while(*str++);
	--str;
	while((*str++ = *src_++ ));
	return dst_;
}

/*count ch in str*/
uint32_t strchrs(const char* str,uint8_t ch){
	ASSERT(str != NULL);
	uint32_t ch_cnt = 0;
	const char* p = str;
	while(*p != 0) {
		if(*p == ch)
			ch_cnt++;
		p++;
	}
	return ch_cnt;
}
